<?php
namespace app\admin\controller;

use app\model\Util;
use support\Request;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
use support\Log;

class UploadController
{
    /**
     * 文件上传
     * @param Request $request
     * @return \support\Response
     */
    public function do(Request $request)
    {
        try {
            $file = $request->file('file');
            if (!$file) {
                return json(['code' => 0, 'msg' => '请选择要上传的文件', 'data' => null]);
            }

            // 获取文件信息
            $ext = $file->getUploadExtension();
            $originalName = $file->getUploadName();

            // 生成保存路径
            $pathInfo = Util::createItemPath('file', $ext, '');
            $file->move($pathInfo['save_path']);

            $conf = config('alicloud.alipay_params');

            $provider = new StaticCredentialsProvider($conf['superAccessKeyId'],$conf['superAccessKeySecret']);

            $config = array(
                "provider" => $provider,
                "endpoint" => $conf['oss']['endpoint'],
                "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
                "region"=> $conf['oss']['region']
            );
            $ossClient = new OssClient($config);

            $options = array(
                OssClient::OSS_HEADERS => array(
                    'x-oss-object-acl' => 'public-read',
                    'x-oss-meta-info' => 'none'
                ),
            );

            $rlt = $ossClient->uploadFile($conf['oss']['bucket'], $pathInfo['web_path'], $pathInfo['save_path'], $options);

            return json([
                'code' => 20000,
                'msg' => '上传成功',
                'data' => [
                    'path' => $pathInfo['web_path'],
                    'url' => Util::pathToUrl($pathInfo['web_path']),
                    'name' => $originalName
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }
}
